# encoding: utf-8
"""
模型相关接口
"""
import traceback
from .config.base import LOG_OPTION, PRINT_TRACEBACK_OPTION
from .center.control import Control
from .config.error import ControlAssemblyError
from loguru import logger
master_controller = Control()


# 错字审查接口
def correct_error(data):
    option = {
        'success': False,
        'error': None,
        'result': None
    }
    try:
        text_infos = data['textInfos']
        result = master_controller.correct_error_text(text_infos)
        option['result'] = result
        option['success'] = True
    except Exception as e:
        if LOG_OPTION:
            logger.error('错字审查错误', exc_info=True)
        if PRINT_TRACEBACK_OPTION:
            traceback.print_exc()
        msg = traceback.format_exc()
        option['error'] = msg
    return option


# 模型训练接口
def train_model(data):
    option = {
        'success': False,
        'error': None,
        'result_msg': None
    }
    try:
        train_task_id = data['train_task_id']
        train_option = master_controller.train_model_task(train_task_id)
        option.update(train_option)
    except:
        if LOG_OPTION:
            logger.error('register user error', exc_info=True)
        if PRINT_TRACEBACK_OPTION:
            traceback.print_exc()
        msg = traceback.format_exc()
        option['error'] = msg
    return option


# 模型预测接口
def predict(data):
    option = {
        'success': False,
        'error': None,
        'result_msg': None
    }
    try:
        model_id = data.get('model', None)
        if model_id == '':
            model_id = None
        infos = data['terms']
        elements = data['elements']
        predict_result = master_controller.predict_elements(model_id, infos, elements)
        option['success'] = predict_result['success']
        option['result'] = predict_result['predict_elements']
        option['error'] = predict_result['error_msg']
    except ControlAssemblyError as e:
        if LOG_OPTION:
            logger.error('要素提取出错', exc_info=True)
        if PRINT_TRACEBACK_OPTION:
            traceback.print_exc()
        msg = str(e)
        option['error'] = '提取要素服务: ' + msg
    except:
        if LOG_OPTION:
            logger.error('register user error', exc_info=True)
        if PRINT_TRACEBACK_OPTION:
            traceback.print_exc()
        msg = traceback.format_exc()
        option['error'] = msg
    return option


# 模型选择接口
def select(data):
    option = {
        'success': False,
        'error': None,
    }
    try:
        model_id = data['model_id']
        result = master_controller.switch_model(model_id)
        option['success'] = result['success']
        option['error'] = result['error_msg']
    except:
        if LOG_OPTION:
            logger.error('合同要素提取出错', exc_info=True)
        if PRINT_TRACEBACK_OPTION:
            traceback.print_exc()
        msg = traceback.format_exc()
        option['error'] = msg
    return option